﻿// =====================================================================
// <copyright file="SettingsManager.cs" author="David R. Guindo">
//    Copyright (C) 2013. All rights reserved.
// </copyright>
// =====================================================================

namespace AppBlock.Config
{
   using System;
   using System.Linq;

   public class SettingsManager
   {
      private SettingsUnitOfWork dataContext;

      private SettingsUnitOfWork DataContext { get { return this.dataContext ?? (this.dataContext = new SettingsUnitOfWork()); } }

      public T Get<T>(string module, string group, T defaultvalue = default(T), params object[] keys)
      {
         string key = String.Join("_", keys);
         var item = this.DataContext.Set<SettingItem>()
            .FirstOrDefault(p => p.Module.ToLower() == module.ToLower()
                            && p.Group == group && p.Key == key);

         if (item != null) return (T)item.GetValue<T>();

         return defaultvalue;
      }

      public T Get<T>(string module, string group, params object[] keys) { return this.Get(module, group, default(T), keys); }

      public void Set<T>(T value, string module, string group, params object[] keys)
      {
         string key = String.Join("_", keys);

         var item = this.DataContext.Set<SettingItem>()
            .FirstOrDefault(p => p.Module.ToLower() == module.ToLower()
                                 && p.Key == key);

         if (item != null)
         {
            this.DataContext.Set<SettingItem>()
               .Attach(item);
            item.SetValue(value);
         }
         else
         {
            item = new SettingItem
                   {
                      Key = key,
                      Module = module,
                   };
            this.DataContext.Set<SettingItem>()
               .Add(item);
         }

         this.DataContext.SaveChanges();
      }
   }
}